/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Controller.List_controller;
import Controller.Values_controller;
import Model.Values_model;
import Utilidades.Utilidades;
import Utilidades.ClientsTableButtonRenderer;
import Utilidades.ClientsTableRenderer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Molina
 */
public class Value_view extends javax.swing.JInternalFrame {

    DefaultTableModel table;
    boolean editable = false;
    private DefaultTableModel datos = null;
    private int numPage = 1;
    /**
     * cantidad de pagina
     */
    private static int CANT_PAGE = -1;
    String lista;
    private static int NUM_RECORDS_PAGE = 10;

    /**
     * Creates new form Value_view
     */
    public Value_view(String cod) {
        initComponents();        
        lista = cod;
        //txtnombre_valor.setText(lista);
        CargarTablaPaginada();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaValores = new javax.swing.JTable();
        jLabelidValor = new javax.swing.JLabel();
        txtnombre_valor = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        btnAgregar = new javax.swing.JButton();
        btnActualizar = new javax.swing.JButton();
        bntNuevo = new javax.swing.JButton();
        btnSiguiente = new javax.swing.JButton();
        btnUltimo = new javax.swing.JButton();
        msgNumPagina = new javax.swing.JLabel();
        btnAnterior = new javax.swing.JButton();
        btnPrimero = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        txtDescripcion_valor = new javax.swing.JTextArea();
        jPanel3 = new javax.swing.JPanel();
        jLabel7 = new javax.swing.JLabel();
        txtbuscar_sede = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setClosable(true);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Gestión de Valores", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Datos Basicos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tablaValores.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código Valor", "Nombre Valor", "Descripcion Valor"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaValores.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaValoresMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tablaValores);

        jPanel2.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 180, 600, 110));
        jPanel2.add(jLabelidValor, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 30, 150, 20));

        txtnombre_valor.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtnombre_valorKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtnombre_valorKeyReleased(evt);
            }
        });
        jPanel2.add(txtnombre_valor, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 60, 150, -1));

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        btnAgregar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/add.png"))); // NOI18N
        btnAgregar.setText("Agregar");
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });
        jPanel4.add(btnAgregar, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 10, 130, 30));

        btnActualizar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnActualizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/update.png"))); // NOI18N
        btnActualizar.setText("Actualizar");
        btnActualizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarActionPerformed(evt);
            }
        });
        jPanel4.add(btnActualizar, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 90, 130, 30));

        bntNuevo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        bntNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/user_add.png"))); // NOI18N
        bntNuevo.setText("Nuevo");
        bntNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bntNuevoActionPerformed(evt);
            }
        });
        jPanel4.add(bntNuevo, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 50, 130, 30));

        jPanel2.add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 30, 250, 130));

        btnSiguiente.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/resultset_next.png"))); // NOI18N
        btnSiguiente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSiguienteActionPerformed(evt);
            }
        });
        jPanel2.add(btnSiguiente, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 300, 40, 30));

        btnUltimo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/resultset_last.png"))); // NOI18N
        btnUltimo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUltimoActionPerformed(evt);
            }
        });
        jPanel2.add(btnUltimo, new org.netbeans.lib.awtextra.AbsoluteConstraints(390, 300, 40, 30));

        msgNumPagina.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        msgNumPagina.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        msgNumPagina.setText("# de #");
        jPanel2.add(msgNumPagina, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 300, 100, 20));

        btnAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/resultset_previous.png"))); // NOI18N
        btnAnterior.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAnteriorActionPerformed(evt);
            }
        });
        jPanel2.add(btnAnterior, new org.netbeans.lib.awtextra.AbsoluteConstraints(200, 300, 40, 30));

        btnPrimero.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/resultset_first.png"))); // NOI18N
        btnPrimero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrimeroActionPerformed(evt);
            }
        });
        jPanel2.add(btnPrimero, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 300, 40, 30));

        jLabel10.setText("Descripcion Valor");
        jPanel2.add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 90, 150, 20));

        jLabel11.setText("Código Valor");
        jPanel2.add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 30, 110, 20));

        jLabel12.setText("Nombre Valor");
        jPanel2.add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 60, 120, 20));

        txtDescripcion_valor.setColumns(20);
        txtDescripcion_valor.setRows(5);
        jScrollPane2.setViewportView(txtDescripcion_valor);

        jPanel2.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 90, 150, 70));

        jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 90, 640, 340));

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel3.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel7.setText("Código Valores");
        jPanel3.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 90, 20));
        jPanel3.add(txtbuscar_sede, new org.netbeans.lib.awtextra.AbsoluteConstraints(130, 10, 160, -1));

        jButton1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/find.png"))); // NOI18N
        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 10, 100, -1));

        jPanel1.add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 30, 640, 50));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 670, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 670, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 0, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 480, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(0, 10, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 460, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 10, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtnombre_valorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnombre_valorKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtnombre_valorKeyPressed

    private void txtnombre_valorKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtnombre_valorKeyReleased
        /*
         * if (!txtnombre_lista.getText().matches("[a-zA-Z]*")) {
         * JOptionPane.showMessageDialog(null, "Datos invalido", "Aviso",
         * JOptionPane.ERROR_MESSAGE); txtnombre_lista.setText(""); }
         */
    }//GEN-LAST:event_txtnombre_valorKeyReleased

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        // TODO add your handling code here:
        String datos[] = new String[8];
        String acum = "";
        String nombre_valor = txtnombre_valor.getText();
        String descripcion_valor = txtDescripcion_valor.getText();
        String id_lista = lista;

        Values_controller lista = new Values_controller("", nombre_valor, descripcion_valor, id_lista);
        try {
            if (txtnombre_valor.getText().equals("")) {
                acum += "Algun campo le quedo incompleto, por favor llenelo" + ".\t\n";
                JOptionPane.showMessageDialog(null, acum);
                return;
            } else {
                System.out.println("Entro");
//                if (V_model.adicionarListas(lista)) {
                if (Values_model.adicionarValores(lista)) {
                    table = (DefaultTableModel) tablaValores.getModel();
                    datos[0] = this.txtnombre_valor.getText();
                    this.txtnombre_valor.setText(null);
                    datos[0] = this.txtDescripcion_valor.getText();
                    this.txtDescripcion_valor.setText(null);
                    table.addRow(datos);
                    limpiarTabla();
                    CargarTablaPaginada();
                    //JOptionPane.showMessageDialog(this, "Registro Adicionado");
                } else {
                    JOptionPane.showMessageDialog(this, "Registro No Adicionado", "", JOptionPane.ERROR_MESSAGE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnActualizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarActionPerformed
        // TODO add your handling code here:
        String id = jLabelidValor.getText();
        String nombre_valor = txtnombre_valor.getText();
        String descripcion_valor = txtDescripcion_valor.getText();
        String id_lista = lista;
        String acum = "";
        try {
            if (txtnombre_valor.getText().equals("")) {
                acum += "Seleccione un Registro de la Tabla Modificarlo" + ".\t\n";
                JOptionPane.showMessageDialog(null, acum);
                return;
            }
            Values_controller valor = new Values_controller(id, nombre_valor, descripcion_valor, id_lista);
            Values_model.modificarValor(valor);
            limpiarTabla();
            CargarTablaPaginada();
            //JOptionPane.showMessageDialog(this, "Registro Actualizado");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnActualizarActionPerformed

    private void bntNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bntNuevoActionPerformed
        // TODO add your handling code here:
        jLabelidValor.setText("");
        txtnombre_valor.setText("");
    }//GEN-LAST:event_bntNuevoActionPerformed

    private void btnSiguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSiguienteActionPerformed
        // TODO add your handling code here:
        if (numPage < CANT_PAGE) {
            numPage++;
        }
        limpiarTabla();
        CargarTablaPaginada();
    }//GEN-LAST:event_btnSiguienteActionPerformed

    private void btnUltimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUltimoActionPerformed
        // TODO add your handling code here:
        numPage = CANT_PAGE;
        limpiarTabla();
        CargarTablaPaginada();
    }//GEN-LAST:event_btnUltimoActionPerformed

    private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnteriorActionPerformed
        // TODO add your handling code here:
        if (numPage > 1) {
            numPage--;
        }
        limpiarTabla();
        CargarTablaPaginada();
    }//GEN-LAST:event_btnAnteriorActionPerformed

    private void btnPrimeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrimeroActionPerformed
        // TODO add your handling code here:
        numPage = 1;
        limpiarTabla();
        CargarTablaPaginada();
    }//GEN-LAST:event_btnPrimeroActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        String buscar = txtbuscar_sede.getText();
        Values_controller lista = Values_model.buscarValor(buscar);

        if (txtbuscar_sede.getText().equals("")) {
            javax.swing.JOptionPane.showMessageDialog(this, "Digite el Registro a Buscar");
            return;
        } else {
            if (lista != null) {
                MoverDatos(lista);
                txtbuscar_sede.setText("");
                //JOptionPane.showMessageDialog(this, "Si encontro el Registro");
            } else {
                JOptionPane.showMessageDialog(this, "No Encontro al Registro");
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void tablaValoresMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaValoresMouseClicked
        // TODO add your handling code here:
        editable = true;
        if (evt.getClickCount() == 2) {
            if (tablaValores.getSelectedRowCount() >= 0) {
                DefaultTableModel tables = (DefaultTableModel) tablaValores.getModel();
                //Asigna a un variable el valor de la tabla seleccionada
                int filamodificada = tablaValores.getSelectedRow();
                //toma los valores de la tabla y los agrega a las cajas de texto
                jLabelidValor.setText(tables.getValueAt(filamodificada, 0).toString());
                txtnombre_valor.setText(tables.getValueAt(filamodificada, 1).toString());
                txtDescripcion_valor.setText(tables.getValueAt(filamodificada, 2).toString());
            }
        }
    }//GEN-LAST:event_tablaValoresMouseClicked

    public void MoverDatos(Values_controller lista) {
        jLabelidValor.setText(lista.getId_valor());
        txtnombre_valor.setText(lista.getNombre_valor());
        txtDescripcion_valor.setText(lista.getDescripcion_valor());
    }

    public void CargarTablaPaginada() {
        try {
            ArrayList<Object[]> data = new ArrayList<Object[]>();
            Utilidades pag = new Utilidades();
            String consulta = "SELECT val_numero, val_nombre, val_descripcion, Listas_lis_numero FROM Valores WHERE Listas_lis_numero = '" +lista+ "' ";
            List lista = pag.ejecutaQueryPaginada(consulta, numPage, NUM_RECORDS_PAGE);
            Integer numeroRegistros = (Integer) lista.get(0);
            float tempNuumPage = (float) numeroRegistros / NUM_RECORDS_PAGE;
            CANT_PAGE = Math.round(tempNuumPage);//((int)tempNuumPage + (Math.round(tempNuumPage)%2 == 0 ? 0 : 1));
            // System.out.println("NUMERO DE REGISTROS TOTALES:" + numeroRegistros.toString());
            msgNumPagina.setText("Pagina " + numPage + " de " + CANT_PAGE);
            /*
             * for (int i = 1; i < lista.size(); i++) { List lista1 = (List)
             * lista.get(i); System.out.println(lista1.toString()); }
             */
            ArrayList unRegistro = null;
            for (int i = 2; i < lista.size(); i++) {
                unRegistro = (ArrayList) lista.get(i);
                Object[] rows = new Object[unRegistro.size()];
                for (int j = 0; j < unRegistro.size(); j++) {
                    rows[j] = unRegistro.get(j);
//                    System.out.println(j+"- "+unRegistro.get(j));
                }
                // rows[2] = "harry";
                data.add(rows);
            }
            table = (DefaultTableModel) this.tablaValores.getModel();
            for (int i = 0; i < data.size(); i++) {
                table.addRow(data.get(i));
            }
            //tablaLista.getColumnModel().getColumn(2).setCellRenderer(new ClientsTableButtonRenderer());
            //tablaLista.getColumnModel().getColumn(2).setCellEditor(new ClientsTableRenderer(new JCheckBox(), this));
            //tablaLista.setPreferredScrollableViewportSize(tablaLista.getPreferredSize());
            //tablaLista.setShowHorizontalLines(true);
            //tablaLista.setShowVerticalLines(false);

        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e.getMessage());
        }
    }

    public void limpiarTabla() {
        table = (DefaultTableModel) tablaValores.getModel();
        try {
            int size = table.getRowCount();
            for (int i = size - 1; i >= 0; i--) {
                table.removeRow(i);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bntNuevo;
    private javax.swing.JButton btnActualizar;
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnAnterior;
    private javax.swing.JButton btnPrimero;
    private javax.swing.JButton btnSiguiente;
    private javax.swing.JButton btnUltimo;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabelidValor;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel msgNumPagina;
    private javax.swing.JTable tablaValores;
    private javax.swing.JTextArea txtDescripcion_valor;
    private javax.swing.JTextField txtbuscar_sede;
    private javax.swing.JTextField txtnombre_valor;
    // End of variables declaration//GEN-END:variables
}
